﻿using Knowledge.EF.Back.Helpers;
using Knowledge.EF.Back.Models;
using Knowledge.EF.Back.Models.DB;
using Knowledge.EF.Back.Models.Users;
using MediatR;

namespace Knowledge.EF.Back.DAL.Users
{
    public class UserRegisterHandler : IRequestHandler<UserRegister, BaseResult>
    {
        private readonly EFCoreContext _context;
        public UserRegisterHandler(EFCoreContext efcorecontext)
        {
            this._context = efcorecontext;
        }
        public Task<BaseResult> Handle(UserRegister request, CancellationToken cancellationToken)
        {
            var cc = JsonConvertHelper.Deserialize<User>(request.param);
            var aa = from aaa in _context.Users where aaa.username == cc.username select aaa;
            if (aa.Count() > 0)
            {
                return Task.FromResult(new BaseResult
                {
                    Code = 201,
                    Message = "用户名重复"
                });
            }
            else
            {

                _context.Add(cc);
                var number = _context.SaveChanges();
                if (number > 0)
                {
                    return Task.FromResult(new BaseResult
                    {
                        Code = 200,
                        Message = "注册成功"
                    });
                }
                else
                {
                    return Task.FromResult(new BaseResult
                    {
                        Code = 201,
                        Message = "注册失败"
                    });
                }

            }
        }
    }
}
